<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\CustomerInfo;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Admin\Renderable\UserTable;
use App\Admin\Renderable\VehicleTable;
use App\Admin\Renderable\ActivityTable;
use App\Models\Activity;
use App\Models\Vehicle;
use App\Admin\Renderable\DealerTable;
use App\Models\Dealer;
use App\Admin\Actions\Show\PushLms;
use App\Models\CustomerInfo as CustomerInfoModel;
use App\Admin\Actions\Grid\ConfirmBuy;
use App\Models\User;

class CustomerInfoController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $model = CustomerInfo::with(['activity', 'vehicle', 'dealer', 'userDraw']);

        return Grid::make($model, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->showColumnSelector();
            $grid->column('id')->sortable();
            $grid->column('user_id')->modal('用户详情', function () {
                return app('App\Admin\Controllers\UserController')->current($this->user_id);
            });
            $grid->column('name');
            $grid->column('phone');
            $grid->column('province');
            $grid->column('city');
            $grid->column('vehicle.name', '车型名')->label();
            $grid->column('activity.title', '活动')->label('default');
            $grid->column('dealer.name', '经销商')->label('default');
            $grid->column('userDraw.id', '是否得到抽奖机会')->display(function ($user_draw_id) {
                return $user_draw_id ? '是' : '否';
            });
            $grid->column('userDraw.prize', '奖品')->display(function ($prize) {
                return $prize ? $prize['name'] : '';
            });
            $grid->column('userDraw.address', '收货地址')->display(function ($address) {
                return is_null($address) ? '' : $address['contact_name'] . ' ' . $address['contact_phone'] . ' ' . $address['contact_address'];
            });
            $grid->column('channel');
            $grid->column('is_push_lms', '是否成功推送LMS')->display(function ($is_push_lms) {
                return $is_push_lms ? '是' : '否';
            });
            $grid->column('referee_id');
            //$grid->column('buy', '确认购车')->action(ConfirmBuy::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (!$this->buy_car_at) {
                    $actions->append(new ConfirmBuy());
                }
            });
            $grid->column('clue_point');
            $grid->column('driver_at');
            $grid->column('driver_point');
            $grid->column('buy_car_at');
            $grid->column('buy_car_point');
            $grid->column('created_at');
            $grid->fixColumns(1);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->equal('id')->integer()->width(2);

                $filter->equal('user_id', '用户')->width(2)
                    ->selectTable(UserTable::make(['id' => ''])) // 设置渲染类实例，并传递自定义参数
                    ->title('用户列表')
                    ->dialogWidth('50%') // 弹窗宽度，默认 800px
                    ->model(User::class, 'id', 'name'); // 设置编辑数据显示

                $filter->equal('name')->width(2);
                $filter->equal('phone')->mobile()->width(2);
                $filter->equal('province')->width(2);
                $filter->equal('city')->width(2);

                $filter->equal('vehicle_id', '车型')->width(2)
                    ->selectTable(VehicleTable::make(['id' => '']))
                    ->title('车型列表')
                    ->dialogWidth('50%')
                    ->model(Vehicle::class, 'id', 'name');

                $filter->equal('activity_id', '活动')->width(3)
                    ->selectTable(ActivityTable::make(['id' => '']))
                    ->title('活动列表')
                    ->dialogWidth('50%')
                    ->model(Activity::class, 'id', 'title');

                $filter->equal('dealer_id', '经销商')->width(3)
                    ->selectTable(DealerTable::make(['id' => '']))
                    ->title('经销商列表')
                    ->dialogWidth('50%')
                    ->model(Dealer::class, 'id', 'name');
                $filter->equal('is_push_lms')->select([1 => '是', 0 => '否'])->width(3);
                $filter->between('created_at')->datetime()->width(4);
                $filter->equal('referee_id', '推荐官')->width(2)
                    ->selectTable(UserTable::make(['id' => ''])) // 设置渲染类实例，并传递自定义参数
                    ->title('用户列表')
                    ->dialogWidth('50%') // 弹窗宽度，默认 800px
                    ->model(User::class, 'id', 'name'); // 设置编辑数据显示
                $filter->where('status', function ($query) {
                    $status = $this->input;
                    switch ($status) {
                        case CustomerInfoModel::RECOMMEND_STATUS_DRIVER:
                            return $query->whereNotNull('driver_at');
                            break;
                        case CustomerInfoModel::RECOMMEND_STATUS_BUY_CAR:
                            return $query->whereNotNull('buy_car_at');
                            break;
                        default:
                            return $query;
                    }
                }, '状态')->select(CustomerInfoModel::$statusMap)->width(2);
                // $filter->scope('status', '已试驾')
                //     ->whereNotNull('driver_at')
                //     ->whereNull('buy_car_at');
            });
            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->scrollbarX();
            $grid->paginate(10);
            // $titles = ['id' => 'ID', 'user_id' => '用户ID', 'name' => '姓名', 'phone' => '手机号', 'province' => '省份', 'city' => '城市', 'service_phone' => '服务电话', 'lng' => '经度', 'lat' => '纬度', 'zaiwang' => '是否在网', 'serieses' => '销售车系'];
            $grid->export()->rows(function ($rows) {
                foreach ($rows as $index => &$row) {
                    $draw = $row->userDraw;
                    $row['userDraw.id'] = isset($draw->id) ? '是' : '否';
                    $row['userDraw.prize'] = isset($draw->prize) ? $draw->prize['name'] : '';
                    $row['userDraw.address'] = isset($draw->address) ? `$draw->address['contact_name'] . ' ' . $draw->address['contact_phone'] . ' ' . $draw->address['contact_address']` : '';
                    $row['is_push_lms'] = $row->is_push_lms ? '是' : '否';
                }
                return $rows;
            })->csv();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {

        $model = CustomerInfo::with(['activity', 'vehicle', 'dealer', 'user']);
        return Show::make($id, $model, function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('name');
            $show->field('phone');
            $show->field('activity.title', '活动');
            $show->field('vehicle.name', '车型');
            $show->field('province');
            $show->field('city');
            $show->field('dealer.name', '经销商');
            $show->field('is_push_lms')->using([0 => '否', 1 => '是']);
            $show->field('clue_point');
            $show->field('driver_at');
            $show->field('driver_point');
            $show->field('buy_car_at');
            $show->field('buy_car_point');

            $show->field('created_at');
            $show->field('updated_at');
            $show->panel()
                ->tools(function ($tools) {
                    $tools->disableEdit();
                    $tools->disableDelete();
                    $tools->append(new PushLms());
                });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CustomerInfo(), function (Form $form) {
            $form->display('id');
            $form->text('user_id');
            $form->selectTable('user_id', '用户')->width(3)
                ->from(UserTable::make(['id' => $form->getKey()]))
                ->title('用户列表')
                ->dialogWidth('50%')
                ->model(User::class, 'id', 'name');
            $form->selectTable('vehicle_id', '车型')->width(3)
                ->from(VehicleTable::make(['id' => $form->getKey()]))
                ->title('车型列表')
                ->dialogWidth('50%')
                ->model(Vehicle::class, 'id', 'name');
            $form->selectTable('activity_id', '活动')->width(3)
                ->from(ActivityTable::make(['id' => $form->getKey()]))
                ->title('活动列表')
                ->dialogWidth('50%')
                ->model(Activity::class, 'id', 'title');
            $form->selectTable('dealer_id', '经销商')->width(3)
                ->from(DealerTable::make(['id' => $form->getKey()]))
                ->title('经销商列表')
                ->dialogWidth('50%')
                ->model(Dealer::class, 'id', 'name');
            $form->text('name');
            $form->text('phone', '手机')
                ->required()
                ->creationRules(['required', 'phone:CN,mobile'])
                ->updateRules(['required', 'phone:CN,mobile']);
            $form->text('province');
            $form->text('city');
        });
    }
}
